package main.java.service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.stereotype.Service;

@Service("jsonService")
public class JsonService {
	/**
	 * 通过ajax, post stringify处理过的json到服务器，
	 * 通过@requestBody接收到的字符串，经过此函数处理后
	 * 还原为原Json数据
	 * @param strJson
	 * @throws UnsupportedEncodingException 
	 */
	public String restoreJsonFromString(String strJson) throws UnsupportedEncodingException		{
		String rawJson = URLDecoder.decode(strJson, "UTF-8");
		String ripeJson = formatJson(rawJson);
		return ripeJson;
	}
	
	private String formatJson(String rawJson) {
		Pattern pattern = Pattern.compile("\\{.*\\}");
		Matcher matcher = pattern.matcher(rawJson);
		if (matcher.find()) {
			return matcher.group();
		}
		throw new RuntimeException(
				"EnrollService.formatJson: not in json format: " + rawJson);
	}
}
